﻿using RRQMCore.ByteManager;
using RRQMSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JsonSocket
{
    public partial class Form1 : Form
    {
        private LanTcpClient Client { get; set; }
        public Form1()
        {
            InitializeComponent();
        }

        private void btSend_Click(object sender, EventArgs e)
        {
            int count = Convert.ToInt32(tbCount.Text);
            for (int i = 0; i < count; i++)
            {
                object obj = new { Id = i, Name = "撒旦发个顺丰" };
                //string msg = "{\"Id\":0,\"Name\":\"撒旦发个顺丰\"}";
                var options = new JsonSerializerOptions();
                options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);
                string msg = JsonSerializer.Serialize(obj,options);
                byte[] send = Encoding.UTF8.GetBytes(msg);
                Client.Send(send);
            }
        }

        private void btConnect_Click(object sender, EventArgs e)
        {
            try
            {
                Client = new LanTcpClient();
                Client.ConnectedService += Client_ConnectedService;
                Client.DisconnectedService += Client_DisconnectedService;
                Client.Connect(new IPHost("127.0.0.1:5600"));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接服务器失败");
            }

        }

        private void Client_DisconnectedService(object sender, MesEventArgs e)
        {
            //LanTcpClient client = (LanTcpClient)sender;
            MessageBox.Show($"连接服务器失败");
        }

        private void Client_ConnectedService(object sender, MesEventArgs e)
        {
            //LanTcpClient client = (LanTcpClient)sender;
            MessageBox.Show($"连接服务器成功");
        }
    }

    class LanTcpClient : TcpClient
    {
        protected override void HandleReceivedData(ByteBlock byteBlock, object obj)
        {
            string msg = Encoding.UTF8.GetString(byteBlock.Buffer, 0, (int)byteBlock.Length);
            Console.WriteLine($"接收的长度是{byteBlock.Length}，位置是{byteBlock.Position},信息是:{msg}");
        }
    }
}
